<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="4">
              <a-form-item label="姓名">
                <a-input
                  v-model="queryParam.cusName"
                  placeholder="请输入客户姓名"
                  allow-clear
                  @keyup.enter.native="handleQuery"
                />
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="电话">
                <a-input
                  v-model="queryParam.phone"
                  placeholder="请输入客户电话"
                  allow-clear
                  @keyup.enter.native="handleQuery"
                />
              </a-form-item>
            </a-col>

            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />刷新</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 增加 -->
      <biz-customer-test-add-form
        v-if="showAddModal"
        ref="bizCustomerTestAddForm"
        @ok="getList"
        @close="showAddModal = false"
      />
      <!-- 编辑 -->
      <biz-customer-test-edit-form
        v-if="showEditModal"
        ref="bizCustomerTestEditForm"
        @ok="getList"
        @close="showEditModal = false"
      />

      <!--跟进记录-->
      <biz-customer-info-shadow-form
        v-if="showShadowModal"
        ref="bizCustomerInfoShadowForm"
        :typeOptions="typeOptions"
        :levelOptions="levelOptions"
        :progressOptions="progressOptions"
        :statusOptions="statusOptions"
        :ideasTypeOptions="ideasTypeOptions"
        :zxInfoOptions="zxInfoOptions"
        :zhichanInfoOptions="zhichanInfoOptions"
        :genjinQuckitInputOptions="genjinQuckitInputOptions"
        :sexOptions="sexOptions"
        :fujianTypeOptions="fujianTypeOptions"
        :carTypeOptions="carTypeOptions"
        @ok="getList"
        @close="showShadowModal = false"
        :eidtshow="true"
      />

      <!--跟进记录-->
      <a-tabs default-active-key="3" @change="callback">
        <a-tab-pane key="3" tab="未跟进待流转（测试）"> </a-tab-pane>
        <a-tab-pane key="1" tab="公海流转" v-if="false"> </a-tab-pane>
        <a-tab-pane key="2" tab="未接待流转"> </a-tab-pane>
      </a-tabs>
      <advance-table
        title="基础"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange,
        }"
        tableKey="base-bizCustomerTest-index-table"
        rowKey="id"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="bizCustomerTestList"
        :loading="loading"
        :format-conditions="true"
        :isShowRefresh="true"
        :isShowColumns="false"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
      >
        <span slot="phone" slot-scope="{ text, record }">
          <a-icon
            type="phone"
            theme="filled"
            style="color: #269f70"
            :rotate="rotate"
            @click="handcallPhone(record)"
          />
          <a @click="handleShadow(record)" v-if="text" style="color: #f56c6c">
            {{ "*******" + text.substring(7, 11) }}
          </a>
          <!-- {{ text }} -->
        </span>
        <span slot="status" slot-scope="{ text }">
          <span>
            {{ text === "0" ? "我的客户" : "线索池" }}
          </span>
        </span>
        <span slot="remainingSeconds" slot-scope="{ text }">
          <span v-if="text <= 3600" style="color: #f56c6c">
            {{ formatSecondsToHHMMSS(text) }}
          </span>
          <span v-else> {{ formatSecondsToHHMMSS(text) }}</span>
        </span>

        <span slot="rowindex" slot-scope="{ index }">
          {{ index + 1 }}
        </span>

        <span slot="notGenjinDays" slot-scope="{ text, record }">
          <span>
            {{ daysDiff(record) }}
          </span>
        </span>
      </advance-table>
    </a-card>
  </div>
</template>
<script>
import {
  playCall,
  findWillToGongHaiList,
  findWeiJieWillToShareList,
  selectToHongHai15,
} from "@/api/biz/bizCustomer";

import {
  delBizCustomerTest,
  exportBizCustomerTest,
} from "@/api/biz/bizCustomerTest";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import BizCustomerTestAddForm from "@/views/biz/customertest/modules/BizCustomerTestAddForm";
import BizCustomerTestEditForm from "@/views/biz/customertest/modules/BizCustomerTestEditForm";
import { findListByCode } from "@/api/biz/sysArea";
import { listDeptTree } from "@/api/system/dept";
import BizCustomerInfoShadowForm from "@/views/biz/customer/modules/BizCustomerInfoShadowForm";
export default {
  name: "BizCustomerTest",
  components: {
    AdvanceTable,
    BizCustomerTestAddForm,
    BizCustomerTestEditForm,
    BizCustomerInfoShadowForm,
  },
  data() {
    return {
      // 状态字典
      statusOptions: [],
      // 申请类型字典
      typeOptions: [],
      // 业务进度
      progressOptions: [],
      levelOptions: [],
      ideasTypeOptions: [],
      // 征信信息
      zxInfoOptions: [],
      zhichanInfoOptions: [],
      genjinQuckitInputOptions: [],
      ownTypeOptions: [],
      fujianTypeOptions: [],
      businessStatusOptions: [],
      carStatusOptions: [],
      // 性别
      sexOptions: [],
      // 当前分页数据的ID数组
      cusListIds: [],
      laiyuanOptions: [],
      rotate: 90,
      showShadowModal: false,
      showAddModal: false,
      showEditModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 基础表格数据
      bizCustomerTestList: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        customerTestType: "3",
      },
      columns: [],
      willColumns: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "50px",
          scopedSlots: { customRender: "rowindex" },
        },

        // {
        //   title: "任务执行时间",
        //   dataIndex: "customerTestCreateTime",
        //   align: "center",
        //   width: "150px",
        // },
        {
          title: "距流转剩余时间",
          dataIndex: "remainingSeconds",
          align: "center",
          width: "150px",
          scopedSlots: { customRender: "remainingSeconds" },
        },

        {
          title: "客户姓名",
          dataIndex: "cusName",
          ellipsis: true,
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "cusName" },
        },
        {
          title: "电话",
          dataIndex: "phone",
          ellipsis: true,
          align: "center",
          width: "100px",
          // fixed: "left",
          scopedSlots: { customRender: "phone" },
        },

        {
          title: "客户来源",
          dataIndex: "laiyuan",
          ellipsis: true,
          align: "center",
          width: "80px",
        },
        {
          title: "客户经理",
          dataIndex: "userName",
          ellipsis: true,
          align: "center",
          width: "100px",
        },
        {
          title: "当前客户位置",
          dataIndex: "status",
          ellipsis: true,
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "status" },
        },

        {
          title: "流转原因",
          dataIndex: "customerToGongHaiReason",
          align: "center",
          width: "300px",
          ellipsis: true,
        },
      ],

      doneColumns: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "50px",
          scopedSlots: { customRender: "rowindex" },
        },

        {
          title: "客户姓名",
          dataIndex: "cusName",
          ellipsis: true,
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "cusName" },
        },
        {
          title: "电话",
          dataIndex: "phone",
          ellipsis: true,
          align: "center",
          width: "100px",
          // fixed: "left",
          scopedSlots: { customRender: "phone" },
        },

        {
          title: "客户来源",
          dataIndex: "laiyuan",
          ellipsis: true,
          align: "center",
          width: "80px",
        },
        {
          title: "客户经理",
          dataIndex: "userName",
          ellipsis: true,
          align: "center",
          width: "100px",
        },

        {
          title: "最后跟进时间",
          dataIndex: "endTime",
          align: "center",
          width: "150px",
        },

        {
          title: "未跟进天数",
          align: "center",
          width: "150px",
          scopedSlots: { customRender: "notGenjinDays" },
        },
        {
          title: "流转原因",
          dataIndex: "customerToGongHaiReason",
          align: "center",
          width: "300px",
          ellipsis: true,
        },
      ],
    };
  },
  created() {
    this.getList();
    this.getDicts("customer_bus_status").then((response) => {
      this.businessStatusOptions = response.data;
    });
    this.getDicts("customer_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("customer_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("bus_progress").then((response) => {
      this.progressOptions = response.data;
    });
    this.getDicts("level_options").then((response) => {
      this.levelOptions = response.data;
    });
    this.getDicts("ideas_type_options").then((response) => {
      this.ideasTypeOptions = response.data;
    });
    this.getDicts("zx_info").then((response) => {
      this.zxInfoOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("zhichan_info").then((response) => {
      this.zhichanInfoOptions = response.data;
    });
    this.getDicts("genjin_quckit_input").then((response) => {
      this.genjinQuckitInputOptions = response.data;
    });
    this.getDicts("own_type").then((response) => {
      this.ownTypeOptions = response.data;
    });
    this.getDicts("fujian_type").then((response) => {
      this.fujianTypeOptions = response.data;
    });
    this.getDicts("car_status_options").then((response) => {
      this.carStatusOptions = response.data;
    });
    this.getDicts("car_type").then((response) => {
      this.carTypeOptions = response.data;
    });
    this.getDicts("to_heimingdan_reason_options").then((response) => {
      this.toHeimingdanReasonOptions = response.data;
    });

    this.handleFindCityList();
    this.getDeptList();
  },
  methods: {
    daysDiff(record) {
      console.log("record", record);
      if (record.endTime == null || record.endTime === "") {
        return "";
      }
      const date1 = new Date(record.endTime);

      const date2 = new Date(); // 结束时间，当前时间
      const diffTime = Math.abs(date2 - date1);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays + "天";
    },
    getDeptList() {
      listDeptTree("", 3, 2).then((response) => {
        // this.expandTree(response.data, 3, this.expandedRowKeys);
        this.deptOptions = response.data;
      });
    },
    // 获取城市区域列表
    handleFindCityList() {
      findListByCode().then((res) => {
        this.cityOptions = res.data;
      });
    },
    // 客户跟踪信息
    handleShadow(record) {
      this.showShadowModal = true;
      this.$nextTick(() =>
        this.$refs.bizCustomerInfoShadowForm.handleShadow(
          record,
          this.cusListIds
        )
      );
    },
    // 格式化秒数为HH:mm:ss
    formatSecondsToHHMMSS(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;

      const pad = (num) => num.toString().padStart(2, "0");
      return `${pad(hours)}小时${pad(minutes)}分${pad(secs)}秒`;
    },
    handcallPhone(item) {
      playCall({ phone: item.phone, id: item.id }).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    /** tab选显卡操作 */
    callback(v) {
      this.queryParam.customerTestType = v;
      this.handleQuery();
    },

    /** 查询基础列表 */
    getList() {
      this.loading = true;

      if (this.queryParam.customerTestType === "1") {
        this.columns = this.willColumns;
        findWillToGongHaiList(this.queryParam).then((response) => {
          this.bizCustomerTestList = response.data.list.map((item, index) => {
            return { ...item, ispop: false, index: index };
          });
          this.cusListIds = response.data.list.map((item, index) => {
            return { id: item.id, index: index };
          });
          this.total = response.data.total;
          this.loading = false;
        });
      } else if (this.queryParam.customerTestType === "2") {
        this.columns = this.willColumns;
        findWeiJieWillToShareList(this.queryParam).then((response) => {
          this.bizCustomerTestList = response.data.list.map((item, index) => {
            return { ...item, ispop: false, index: index };
          });
          this.cusListIds = response.data.list.map((item, index) => {
            return { id: item.id, index: index };
          });
          this.total = response.data.total;
          this.loading = false;
        });
      } else if (this.queryParam.customerTestType === "3") {
        this.columns = this.doneColumns;
        selectToHongHai15(this.queryParam).then((response) => {
          this.bizCustomerTestList = response.data.list.map((item, index) => {
            return { ...item, ispop: false, index: index };
          });
          this.cusListIds = response.data.list.map((item, index) => {
            return { id: item.id, index: index };
          });
          this.total = response.data.total;
          this.loading = false;
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd() {
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.bizCustomerTestAddForm.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.bizCustomerTestEditForm.handleUpdate(record, ids)
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const bizCustomerTestIds = row.id || this.ids;
      this.$confirm({
        title: "确认删除所选中数据?",
        onOk() {
          return delBizCustomerTest(bizCustomerTestIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportBizCustomerTest(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
  },
};
</script>
